package org.zjx.analysis.analyze.battle;

import lombok.Data;
import org.zjx.command.util.ImageUtil;
import org.zjx.window.window.IWindow;
import org.zjx.command.entity.Character;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;


@Data
public class BattleAnalysis {
    protected final BufferedImage screenshot;
    private boolean isBattle;
    private List<Character> otherSide; //敌方
    private List<Character> ourSide; //我方
    private BattleStatus battleStatus = BattleStatus.AWAITING;

    private List<Point> bloodPoints;

    public enum BattleStatus {
        AWAITING,   //等待中
        COUNTDOWN,  //倒计时
        PERFORMED   //执行中
    }


    private static final List<Rectangle> otherSidesNameAreas = Arrays.asList(
            ImageUtil.createRect(167, 209, 368, 229),
            ImageUtil.createRect(230, 169, 432, 188),
            ImageUtil.createRect(123, 249, 287, 268),
            ImageUtil.createRect(288, 129, 477, 148),
            ImageUtil.createRect(49, 289, 249, 310),
            ImageUtil.createRect(223, 260, 424, 280),
            ImageUtil.createRect(283, 220, 476, 238),
            ImageUtil.createRect(170, 300, 347, 318),
            ImageUtil.createRect(348, 180, 532, 199),
            ImageUtil.createRect(107, 340, 293, 357));


    private static final List<Rectangle> ourSidesNameAreas = Arrays.asList(
            ImageUtil.createRect(431, 418, 631, 438),
            ImageUtil.createRect(494, 378, 694, 397),
            ImageUtil.createRect(375, 457, 575, 471),
            ImageUtil.createRect(557, 334, 757, 360),
            ImageUtil.createRect(342, 500, 542, 514),
            ImageUtil.createRect(401, 368, 601, 388),
            ImageUtil.createRect(484, 328, 684, 347),
            ImageUtil.createRect(365, 407, 565, 421),
            ImageUtil.createRect(544, 284, 744, 310),
            ImageUtil.createRect(312, 450, 512, 464));

    public static BufferedImage autoMatic = ImageUtil.createImage("iVBORw0KGgoAAAANSUhEUgAAADEAAAARCAYAAAB0MEQqAAAEBElEQVR42r2WIXTbSBCGBQ0NDhgUGBwQCBAIECgQMDAIEAgQCBA0KDAoECgIOGBQEFAgWHDAoMAwoCDggKFBQUBBwAG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wIlEZ3t5XmJ0BNPYnXlXy5jEg76JXYGdpmLEfCc6dAFDGdfA3ZFOvjiX/rn+Opi8fyif1bzvPAr8IPDtRMPDUamw0W0BpSD/RBlfP4FIp398PmYTeQXweMY+Xwi6WzCxfYvDS8lV6SvJ/9/IM6zXvgK0lJJOkskc4yyN4kys9XA/jUM7eKzY/5+9nws7g/PtAKJzH+ZyHw6kX8B/T7aVpEYCIMAAAAASUVORK5CYII=");
    public static BufferedImage bloodHalfImage = ImageUtil.createImage("iVBORw0KGgoAAAANSUhEUgAAABMAAAAGCAYAAAAhS6XkAAAAO0lEQVR42mP48GfDfzD+seH/iy8QDGLDxYH4BRLGxodhBpBGBmoBkEuoZhhVXQb2KzVdhh6opGDkCAAA9F6Wi44JWlYAAAAASUVORK5CYII=");


    public final Color normalNameColor = new Color(86, 223, 109);
    public final Color clickNameColor = new Color(255, 0, 0);

    public final Rectangle awaitArea = ImageUtil.createRect(365, 64, 454, 67);
    public final Rectangle countArea = ImageUtil.createRect(365, 68, 454, 81);

    public BattleAnalysis(BufferedImage screenshot) {
        this.screenshot = copy(screenshot);
        otherSide = new ArrayList<>(10);
        ourSide = new ArrayList<>(10);

        // 预填充10个null元素
        for (int i = 0; i < 10; i++) {
            otherSide.add(null);
            ourSide.add(null);
        }

        analysis();
    }

    private void analysisInformation() {
        BufferedImage awaitImage = ImageUtil.cutImage(screenshot, awaitArea);
        BufferedImage countImage = ImageUtil.cutImage(screenshot, countArea);
        if (ImageUtil.haveColor(countImage, Collections.singletonList(new Color(248,252,248)))) {
            battleStatus = BattleStatus.COUNTDOWN;
        } else if (ImageUtil.haveColor(awaitImage, Collections.singletonList(new Color(248,252,248)))) {
            battleStatus = BattleStatus.AWAITING;
        } else {
            battleStatus = BattleStatus.PERFORMED;
        }
    }

    private BufferedImage copy(BufferedImage screenshot) {
        // 创建副本，以避免对原图像产生影响
        BufferedImage copy = new BufferedImage(screenshot.getWidth(), screenshot.getHeight(), BufferedImage.TYPE_INT_ARGB);
        copy.getGraphics().drawImage(screenshot, 0, 0, null);
        return copy;
    }

    private void analysis() {
        this.isBattle = isInBattle();
        if (!isBattle) return;
        analysisInformation();
        if (battleStatus == BattleStatus.PERFORMED) return;
        distinguishOtherSide();
    }

    //识别敌方 名称等信息
    public void distinguishOtherSide() {
        for (int i = 0; i < otherSidesNameAreas.size(); i++) {
            Character character = analysisCharacter(true, i);
            if (character == null) continue;
            character.setPosition(i);
            otherSide.set(i, character);
        }

        bloodPoints = ImageUtil.matchTemplate(screenshot, bloodHalfImage);

    }

    //获取点击区域
    public Rectangle getOtherSideChooseArea(int index) {
        Rectangle rectangle = otherSidesNameAreas.get(index);
        return new Rectangle(rectangle.x - 30, rectangle.y - 120, rectangle.width + 60, rectangle.height + 100);
    }

    public Character analysisCharacter(boolean otherSide, int position) {
        Rectangle rectangle = otherSide ? otherSidesNameAreas.get(position) : ourSidesNameAreas.get(position);
        int width = rectangle.width;
        Rectangle nameArea = new Rectangle(rectangle.x + width / 3, rectangle.y, rectangle.width / 3, rectangle.height);
        BufferedImage nameImage = ImageUtil.cutImage(screenshot, nameArea);
        if (!ImageUtil.haveColor(nameImage, Arrays.asList(normalNameColor, clickNameColor))) return null;

        Character character = new Character();
        character.setMonster(otherSide);
        if (ImageUtil.haveColor(nameImage, Collections.singletonList(clickNameColor))) {
            character.setChoose(true);
            //TODO 可在这里添加识别名称逻辑（已选中）
        }

        if (!otherSide) {
            character.setHpPercentage(ourSideBloodForIndex(position));
        }

        return character;
    }

    public int ourSideBloodForIndex(int position) {
        Rectangle rectangle = ourSidesNameAreas.get(position);
        Integer bloodPercentage = ourBloodByPosition(rectangle);
        return bloodPercentage == null ? 0 : bloodPercentage;
    }

    private Integer ourBloodByPosition(Rectangle nameRectangle) {
        if (bloodPoints == null) return null;
        Point closestRightPoint = null;
        int minX = Integer.MAX_VALUE;

        // 找到在rectangle.x右边且最左边的点（x坐标最小）
        for (Point point : bloodPoints) {
            if (point.x > nameRectangle.x && point.x < minX) {
                minX = point.x;
                closestRightPoint = point;
            }
        }
        if (closestRightPoint == null) return null;
        Rectangle rect = new Rectangle(closestRightPoint.x + 1, closestRightPoint.y + 3, 36, 1);
        BufferedImage image = ImageUtil.cutImage(screenshot, rect);

        int blood = 0;
        for (int j = 0; j < image.getWidth(); j++) {
            if (image.getRGB(j, 0) == new Color(240, 0, 8).getRGB()) {
                blood++;
            }
        }
        return blood * 100 / image.getWidth();
    }


    //判断是否选中
    public boolean isCharacterChoose(boolean otherSide, int index) {
        Character character = otherSide ? this.otherSide.get(index) : ourSide.get(index);
        if (character == null) return false;
        return character.isChoose();
    }

    public boolean isPetOperation() {
        List<Point> points = ImageUtil.matchTemplate(screenshot, autoMatic);
        return battleStatus == BattleStatus.AWAITING && points.isEmpty();
    }

    private boolean isInBattle() {
        Color targetColor1 = new Color(224, 204, 160);
        Color targetColor2 = new Color(184, 160, 112);

        // 检查第一组坐标点
        boolean firstGroupMatch = screenshot.getRGB(788, 122) == targetColor1.getRGB() && screenshot.getRGB(797, 122) == targetColor1.getRGB();

        // 检查第二组坐标点
        boolean secondGroupMatch = screenshot.getRGB(788, 382) == targetColor2.getRGB() && screenshot.getRGB(797, 382) == targetColor2.getRGB();

        // 任意一组匹配即返回 true
        return firstGroupMatch || secondGroupMatch;
    }

}
